import os
import requests
import json
import logging
from dotenv import load_dotenv
from flask import Flask, request, jsonify
from flask_cors import CORS

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='offline_content_debug.log',
    filemode='a'
)
logger = logging.getLogger('offline_content')

# 调试模式标志
DEBUG_MODE = True

# 加载环境变量
load_dotenv()

app = Flask(__name__, static_folder='static', static_url_path='')
CORS(app)  # 允许跨域请求

# 获取API密钥
# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
OPENAI_API_KEY = "jina_b8e7dd0e5f7a45ecb03429f5dcc5de92ZREJN73p43A6UNZ5jsnjm7PnCT7A"
if not OPENAI_API_KEY:
    raise ValueError("请在.env文件中设置OPENAI_API_KEY")

# API端点
# OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_URL = "https://deepsearch.jina.ai/v1/chat/completions"

# 翻译API
@app.route('/api/translate', methods=['POST'])
def translate():
    data = request.json
    source_text = data.get('text', '')
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'en')
    
    if not source_text:
        return jsonify({"error": "请提供要翻译的文本"}), 400
    
    # 构建提示
    prompt = f"请将以下{source_lang}文本翻译成{target_lang}，保持原文的意思、风格和语气：\n\n{source_text}"
    
    # 调用OpenAI API
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {"role": "system", "content": "你是一个专业的翻译助手，擅长准确翻译各种语言。"},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.3
    }
    
    try:
        response = requests.post(OPENAI_API_URL, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()
        translated_text = result["choices"][0]["message"]["content"]
        
        return jsonify({
            "translated_text": translated_text,
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 文化知识查询API
@app.route('/api/culture', methods=['POST'])
def culture_info():
    data = request.json
    query = data.get('query', '')
    location = data.get('location', '')
    language = data.get('language', 'zh')
    
    if not query and not location:
        return jsonify({"error": "请提供查询内容或位置"}), 400
    
    # 构建提示
    if location:
        prompt = f"请提供关于{location}的以下文化知识：{query}。请用{language}回答。"
    else:
        prompt = f"请提供关于以下文化问题的信息：{query}。请用{language}回答。"
    
    # 调用OpenAI API
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {"role": "system", "content": "你是一个专业的文化历史顾问，擅长提供准确、简洁的文化和历史知识。"},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7
    }
    
    try:
        response = requests.post(OPENAI_API_URL, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()
        culture_info = result["choices"][0]["message"]["content"]
        
        return jsonify({
            "culture_info": culture_info,
            "query": query,
            "location": location
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 语言学习API
@app.route('/api/language_learning', methods=['POST'])
def language_learning():
    data = request.json
    target_language = data.get('target_language', 'en')
    learning_type = data.get('learning_type', 'phrases')  # phrases, conversation, vocabulary
    difficulty = data.get('difficulty', 'beginner')  # beginner, intermediate, advanced
    context = data.get('context', '旅行')  # 学习场景
    
    # 构建提示
    if learning_type == 'phrases':
        prompt = f"请提供10个在{context}场景中最常用的{target_language}短语，包括发音指导和中文翻译。难度级别：{difficulty}。"
    elif learning_type == 'conversation':
        prompt = f"请创建一个{context}场景下的{target_language}对话示例，难度级别：{difficulty}。包括中文翻译和关键词解释。"
    else:  # vocabulary
        prompt = f"请提供15个{context}场景中最常用的{target_language}词汇，包括发音、词性和中文翻译。难度级别：{difficulty}。"
    
    # 调用OpenAI API
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {"role": "system", "content": "你是一个专业的语言教师，擅长创建实用的语言学习材料。"},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7
    }
    
    try:
        response = requests.post(OPENAI_API_URL, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()
        learning_content = result["choices"][0]["message"]["content"]
        
        return jsonify({
            "learning_content": learning_content,
            "target_language": target_language,
            "learning_type": learning_type,
            "difficulty": difficulty,
            "context": context
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 可用目的地API
@app.route('/api/available_destinations', methods=['GET'])
def available_destinations():
    # 当前开放的目的地
    available = {
        'tokyo': {
            'name': '东京',
            'country': '日本',
            'language': 'ja',
            'available': True,
            'packages': ['language', 'map', 'culture'],
            'languageSize': 45,
            'mapSize': 85,
            'cultureSize': 30
        },
        'paris': {
            'name': '巴黎',
            'country': '法国',
            'language': 'fr',
            'available': True,
            'packages': ['language', 'map', 'culture'],
            'languageSize': 50,
            'mapSize': 90,
            'cultureSize': 35
        },
        'newyork': {
            'name': '纽约',
            'country': '美国',
            'language': 'en',
            'available': True,
            'packages': ['language', 'map', 'culture'],
            'languageSize': 40,
            'mapSize': 95,
            'cultureSize': 32
        },
        'rome': {
            'name': '罗马',
            'country': '意大利',
            'language': 'it',
            'available': False,
            'coming_soon': True,
            'eta': '2025年7月'
        },
        'bangkok': {
            'name': '曼谷',
            'country': '泰国',
            'language': 'th',
            'available': False,
            'coming_soon': True,
            'eta': '2025年8月'
        },
        'london': {
            'name': '伦敦',
            'country': '英国',
            'language': 'en',
            'available': False,
            'coming_soon': True,
            'eta': '2025年9月'
        }
    }
    
    return jsonify({
        'destinations': available,
        'total_available': 3,
        'coming_soon': 3
    })

import os
import zipfile
import time
import threading
from pathlib import Path

# 离线内容包下载API
@app.route('/api/download_package', methods=['POST'])
def download_package():
    logger.debug(f"收到下载请求: {request.json}")
    data = request.json
    destination = data.get('destination', '')
    package_type = data.get('package_type', '')
    
    # 检查目的地是否可用
    destinations = {
        'tokyo': {
            'name': '东京',
            'country': '日本',
            'language': 'ja',
            'available': True
        },
        'paris': {
            'name': '巴黎',
            'country': '法国',
            'language': 'fr',
            'available': True
        },
        'newyork': {
            'name': '纽约',
            'country': '美国',
            'language': 'en',
            'available': True
        },
        'rome': {
            'name': '罗马',
            'country': '意大利',
            'language': 'it',
            'available': False,
            'eta': '2025年7月'
        },
        'bangkok': {
            'name': '曼谷',
            'country': '泰国',
            'language': 'th',
            'available': False,
            'eta': '2025年8月'
        },
        'london': {
            'name': '伦敦',
            'country': '英国',
            'language': 'en',
            'available': False,
            'eta': '2025年9月'
        }
    }
    
    if not destination or not package_type:
        logger.warning(f"请求缺少必要参数: destination={destination}, package_type={package_type}")
        return jsonify({"error": "请提供目的地和包类型"}), 400
    
    if destination not in destinations:
        logger.warning(f"不支持的目的地: {destination}")
        return jsonify({"error": "不支持的目的地"}), 400
    
    if not destinations[destination]['available']:
        logger.info(f"请求了未开放的目的地: {destination}")
        return jsonify({
            "error": "目的地暂不可用",
            "destination": destination,
            "name": destinations[destination]['name'],
            "eta": destinations[destination]['eta']
        }), 400
    
    if package_type not in ['language', 'map', 'culture']:
        logger.warning(f"不支持的包类型: {package_type}")
        return jsonify({"error": "不支持的包类型"}), 400
    
    # 生成唯一下载ID
    download_id = f"{destination}_{package_type}_{int(time.time())}"
    logger.info(f"生成下载ID: {download_id}")
    
    # 包大小信息
    package_sizes = {
        'tokyo': {'language': 45, 'map': 85, 'culture': 30},
        'paris': {'language': 50, 'map': 90, 'culture': 35},
        'newyork': {'language': 40, 'map': 95, 'culture': 32}
    }
    
    # 创建离线内容目录
    offline_dir = Path("offline_content")
    offline_dir.mkdir(exist_ok=True)
    logger.debug(f"创建离线内容目录: {offline_dir}")
    
    # 在后台线程中生成内容
    threading.Thread(
        target=generate_offline_content,
        args=(download_id, destination, package_type, destinations[destination])
    ).start()
    
    # 返回下载信息
    return jsonify({
        "success": True,
        "destination": destination,
        "package_type": package_type,
        "size_mb": package_sizes[destination][package_type],
        "download_id": download_id,
        "status_url": f"/api/download_status/{download_id}"
    })

# 下载状态API
@app.route('/api/download_status/<download_id>', methods=['GET'])
def download_status(download_id):
    # 解析下载ID
    try:
        parts = download_id.split('_')
        destination = parts[0]
        package_type = parts[1]
    except:
        return jsonify({"error": "无效的下载ID"}), 400
    
    # 检查文件是否已生成
    offline_dir = Path("offline_content")
    zip_file = offline_dir / f"{download_id}.zip"
    
    if zip_file.exists():
        return jsonify({
            "status": "completed",
            "download_url": f"/api/download_file/{download_id}",
            "destination": destination,
            "package_type": package_type
        })
    else:
        # 检查是否正在生成
        temp_file = offline_dir / f"{download_id}.generating"
        if temp_file.exists():
            # 读取进度
            try:
                with open(temp_file, 'r') as f:
                    progress = f.read().strip()
                    progress = int(progress) if progress.isdigit() else 0
            except:
                progress = 0
                
            return jsonify({
                "status": "generating",
                "progress": progress,
                "destination": destination,
                "package_type": package_type
            })
        else:
            return jsonify({
                "status": "not_found",
                "error": "下载任务不存在或已过期"
            }), 404

# 文件下载API
@app.route('/api/download_file/<download_id>', methods=['GET'])
def download_file(download_id):
    from flask import send_file
    
    offline_dir = Path("offline_content")
    zip_file = offline_dir / f"{download_id}.zip"
    
    if zip_file.exists():
        return send_file(
            zip_file,
            mimetype='application/zip',
            as_attachment=True,
            download_name=f"{download_id}.zip"
        )
    else:
        return jsonify({"error": "文件不存在"}), 404

# 生成离线内容
def generate_offline_content(download_id, destination, package_type, destination_info):
    offline_dir = Path("offline_content")
    temp_file = offline_dir / f"{download_id}.generating"
    zip_file = offline_dir / f"{download_id}.zip"
    content_dir = offline_dir / download_id
    
    try:
        # 创建临时文件记录进度
        with open(temp_file, 'w') as f:
            f.write("0")
        
        # 创建内容目录
        content_dir.mkdir(exist_ok=True)
        
        # 根据包类型生成不同内容
        if package_type == 'language':
            generate_language_package(content_dir, destination, destination_info, temp_file)
        elif package_type == 'culture':
            generate_culture_package(content_dir, destination, destination_info, temp_file)
        elif package_type == 'map':
            generate_map_package(content_dir, destination, destination_info, temp_file)
        
        # 创建ZIP文件
        with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for file in content_dir.glob('**/*'):
                if file.is_file():
                    zipf.write(file, file.relative_to(content_dir))
        
        # 更新进度为100%
        with open(temp_file, 'w') as f:
            f.write("100")
            
    except Exception as e:
        # 记录错误
        with open(offline_dir / f"{download_id}_error.log", 'w') as f:
            f.write(str(e))
    finally:
        # 清理临时文件和目录
        import shutil
        if content_dir.exists():
            shutil.rmtree(content_dir)

# 生成语言包
def generate_language_package(content_dir, destination, destination_info, progress_file):
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    # 目的地信息
    dest_name = destination_info['name']
    country = destination_info['country']
    language = destination_info['language']
    
    # 生成常用短语
    phrases_prompt = f"请提供在{dest_name}({country})旅行时最常用的30个{language}短语，包括发音指导和中文翻译。格式为JSON数组，每个对象包含phrase(原文)、pronunciation(发音)、translation(中文翻译)和usage(使用场景)字段。"
    phrases = generate_content_with_llm(phrases_prompt, "你是一个专业的语言教师，擅长创建实用的语言学习材料。")
    
    # 保存常用短语
    with open(content_dir / "phrases.json", 'w', encoding='utf-8') as f:
        f.write(phrases)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("30")
    
    # 生成对话示例
    conversations_prompt = f"请创建5个在{dest_name}({country})旅行时可能遇到的{language}对话示例，包括中文翻译。场景包括餐厅、酒店、交通、购物和紧急情况。格式为JSON数组，每个对象包含scenario(场景)、conversation(对话数组，每项包含speaker和text)和translations(对话翻译数组)。"
    conversations = generate_content_with_llm(conversations_prompt, "你是一个专业的语言教师，擅长创建实用的语言学习材料。")
    
    # 保存对话示例
    with open(content_dir / "conversations.json", 'w', encoding='utf-8') as f:
        f.write(conversations)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("50")
    
    # 生成词汇表
    vocabulary_prompt = f"请提供在{dest_name}({country})旅行时最常用的50个{language}词汇，包括发音、词性和中文翻译。格式为JSON数组，每个对象包含word(词汇)、pronunciation(发音)、part_of_speech(词性)、translation(中文翻译)和example(示例句子)字段。"
    vocabulary = generate_content_with_llm(vocabulary_prompt, "你是一个专业的语言教师，擅长创建实用的语言学习材料。")
    
    # 保存词汇表
    with open(content_dir / "vocabulary.json", 'w', encoding='utf-8') as f:
        f.write(vocabulary)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("70")
    
    # 生成语言包信息
    info = {
        "destination": destination,
        "name": dest_name,
        "country": country,
        "language": language,
        "package_type": "language",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["phrases.json", "conversations.json", "vocabulary.json"]
    }
    
    # 保存语言包信息
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")

# 生成文化包
def generate_culture_package(content_dir, destination, destination_info, progress_file):
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    # 目的地信息
    dest_name = destination_info['name']
    country = destination_info['country']
    
    # 生成历史背景
    history_prompt = f"请提供关于{dest_name}({country})的详细历史背景，包括重要历史事件、文化演变和对现代社会的影响。格式为JSON对象，包含title(标题)、overview(概述)和sections(章节数组，每个章节包含subtitle和content)。"
    history = generate_content_with_llm(history_prompt, "你是一个专业的历史学者，擅长提供准确、简洁的历史知识。")
    
    # 保存历史背景
    with open(content_dir / "history.json", 'w', encoding='utf-8') as f:
        f.write(history)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("30")
    
    # 生成文化习俗
    customs_prompt = f"请提供关于{dest_name}({country})的文化习俗、礼仪和禁忌，包括社交规范、餐桌礼仪、服饰要求和重要节日。格式为JSON对象，包含title(标题)、overview(概述)和sections(章节数组，每个章节包含subtitle和content)。"
    customs = generate_content_with_llm(customs_prompt, "你是一个专业的文化顾问，擅长提供准确的文化习俗和礼仪知识。")
    
    # 保存文化习俗
    with open(content_dir / "customs.json", 'w', encoding='utf-8') as f:
        f.write(customs)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("50")
    
    # 生成景点介绍
    attractions_prompt = f"请提供{dest_name}({country})的10个主要景点介绍，包括历史背景、文化意义和实用信息。格式为JSON数组，每个对象包含name(名称)、description(描述)、history(历史)、cultural_significance(文化意义)和practical_info(实用信息)字段。"
    attractions = generate_content_with_llm(attractions_prompt, "你是一个专业的旅游顾问，擅长提供景点的历史文化背景和实用信息。")
    
    # 保存景点介绍
    with open(content_dir / "attractions.json", 'w', encoding='utf-8') as f:
        f.write(attractions)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("70")
    
    # 生成文化包信息
    info = {
        "destination": destination,
        "name": dest_name,
        "country": country,
        "package_type": "culture",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["history.json", "customs.json", "attractions.json"]
    }
    
    # 保存文化包信息
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")

# 生成地图包
def generate_map_package(content_dir, destination, destination_info, progress_file):
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    # 目的地信息
    dest_name = destination_info['name']
    country = destination_info['country']
    
    # 生成POI数据
    poi_prompt = f"请提供{dest_name}({country})的30个主要兴趣点(POI)数据，包括景点、餐厅、酒店和交通枢纽。格式为JSON数组，每个对象包含id、name(名称)、type(类型)、coordinates(坐标，格式为[经度,纬度])、address(地址)和description(描述)字段。"
    pois = generate_content_with_llm(poi_prompt, "你是一个专业的地理信息专家，擅长提供准确的位置数据和描述。")
    
    # 保存POI数据
    with open(content_dir / "pois.json", 'w', encoding='utf-8') as f:
        f.write(pois)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("40")
    
    # 生成路线数据
    routes_prompt = f"请提供{dest_name}({country})的5条经典旅游路线，每条路线包含多个景点。格式为JSON数组，每个对象包含name(路线名称)、description(描述)、duration(时长)和points(路线点数组，每个点包含poi_id、name和stay_time字段)。"
    routes = generate_content_with_llm(routes_prompt, "你是一个专业的旅游规划师，擅长设计最佳旅游路线。")
    
    # 保存路线数据
    with open(content_dir / "routes.json", 'w', encoding='utf-8') as f:
        f.write(routes)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("70")
    
    # 生成地图包信息
    info = {
        "destination": destination,
        "name": dest_name,
        "country": country,
        "package_type": "map",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["pois.json", "routes.json"],
        "map_bounds": {
            "northeast": {"lat": 0, "lng": 0},  # 这里应该填入实际的地图边界
            "southwest": {"lat": 0, "lng": 0}
        }
    }
    
    # 保存地图包信息
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")

# 使用LLM生成内容
def generate_content_with_llm(prompt, system_prompt):
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7
    }
    
    try:
        response = requests.post(OPENAI_API_URL, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        return content
    except Exception as e:
        print(f"生成内容失败: {str(e)}")
        # 返回一个简单的错误JSON
        return json.dumps({"error": str(e)})

# 管理存储空间API
@app.route('/api/storage/info', methods=['GET'])
def storage_info():
    offline_dir = Path("offline_content")
    
    # 计算已使用空间
    used_space = 0
    downloaded_packages = []
    
    if offline_dir.exists():
        # 统计ZIP文件大小
        for zip_file in offline_dir.glob("*.zip"):
            file_size = zip_file.stat().st_size
            used_space += file_size
            
            # 解析包信息
            download_id = zip_file.stem
            parts = download_id.split('_')
            if len(parts) >= 2:
                destination = parts[0]
                package_type = parts[1]
                
                # 获取目的地信息
                destinations = {
                    'tokyo': {'name': '东京', 'country': '日本', 'language': 'ja'},
                    'paris': {'name': '巴黎', 'country': '法国', 'language': 'fr'},
                    'newyork': {'name': '纽约', 'country': '美国', 'language': 'en'}
                }
                
                dest_info = destinations.get(destination, {'name': destination, 'country': '未知'})
                
                downloaded_packages.append({
                    "id": download_id,
                    "destination": destination,
                    "name": dest_info['name'],
                    "package_type": package_type,
                    "size": file_size,
                    "download_date": time.strftime("%Y-%m-%d", time.localtime(zip_file.stat().st_mtime))
                })
    
    # 转换为MB
    used_space_mb = round(used_space / (1024 * 1024), 2)
    
    return jsonify({
        "used_space": used_space,
        "used_space_mb": used_space_mb,
        "packages": downloaded_packages,
        "package_count": len(downloaded_packages)
    })

# 删除离线内容包API
@app.route('/api/storage/delete/<download_id>', methods=['DELETE'])
def delete_package(download_id):
    offline_dir = Path("offline_content")
    zip_file = offline_dir / f"{download_id}.zip"
    
    if zip_file.exists():
        try:
            zip_file.unlink()
            logger.info(f"删除离线内容包: {download_id}")
            return jsonify({"success": True, "message": f"已删除内容包: {download_id}"})
        except Exception as e:
            logger.error(f"删除内容包失败: {download_id} - {str(e)}")
            return jsonify({"error": f"删除失败: {str(e)}"}), 500
    else:
        return jsonify({"error": "内容包不存在"}), 404

# 获取文化知识库API
@app.route('/api/culture/<destination>', methods=['GET'])
def get_culture_info(destination):
    offline_dir = Path("offline_content")
    
    # 查找该目的地的文化包
    culture_packages = list(offline_dir.glob(f"{destination}_culture_*.zip"))
    
    if not culture_packages:
        return jsonify({
            "error": "离线文化数据不可用",
            "message": "请先下载文化知识库"
        }), 404
    
    # 使用最新的文化包
    latest_package = sorted(culture_packages, key=lambda x: x.stat().st_mtime, reverse=True)[0]
    
    try:
        # 解压并读取文化数据
        with zipfile.ZipFile(latest_package, 'r') as zip_ref:
            with zip_ref.open('info.json') as f:
                info = json.load(f)
            
            with zip_ref.open('history.json') as f:
                history = json.load(f)
            
            # 如果存在风俗习惯文件
            customs = None
            if 'customs.json' in [file.filename for file in zip_ref.filelist]:
                with zip_ref.open('customs.json') as f:
                    customs = json.load(f)
        
        return jsonify({
            "destination": destination,
            "name": info["name"],
            "country": info["country"],
            "history": history,
            "customs": customs,
            "version": info.get("version", "1.0"),
            "updated_at": info.get("created_at", "未知")
        })
    except Exception as e:
        logger.error(f"读取文化数据失败: {destination} - {str(e)}")
        return jsonify({
            "error": "读取文化数据失败",
            "message": str(e)
        }), 500

# 主页路由
@app.route('/')
def index():
    return app.send_static_file('index.html')

# 情境化翻译建议API
@app.route('/api/translate/contextual', methods=['POST'])
def contextual_translation():
    data = request.json
    text = data.get('text', '')
    context = data.get('context', '')
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'zh')
    
    if not text:
        return jsonify({"error": "请提供需要翻译的文本"}), 400
    
    # 调用LLM提供情境化翻译
    system_prompt = "你是一个专业的翻译助手，请根据用户提供的情境，给出最适合该情境的翻译。"
    
    prompt = f"""请根据以下情境，提供最适合的翻译：

原文: {text}
情境: {context}
源语言: {source_lang}
目标语言: {target_lang}

请提供以下内容:
1. 直译
2. 情境化翻译（考虑文化背景和使用场景）
3. 替代表达（如有更地道的表达方式）
4. 文化注释（如有必要）

以JSON格式返回，格式为:
{{
  "literal": "直译",
  "contextual": "情境化翻译",
  "alternatives": ["替代表达1", "替代表达2"],
  "cultural_notes": "文化注释"
}}
"""
    
    try:
        result = generate_content_with_llm(prompt, system_prompt)
        
        # 尝试解析JSON
        try:
            translation = json.loads(result)
        except:
            # 如果不是JSON格式，返回原始结果
            translation = {"result": result}
        
        return jsonify({
            "original": text,
            "context": context,
            "translations": translation,
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    except Exception as e:
        logger.error(f"情境化翻译失败: {str(e)}")
        return jsonify({"error": f"情境化翻译失败: {str(e)}"}), 500

if __name__ == '__main__':
    app.run(debug=False, port=8000)